package pl.polidea.imf.blackberry.util;

import java.io.IOException;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import microlog.net.sf.microlog.core.Logger;
import microlog.net.sf.microlog.core.LoggerFactory;

public class FileSystemHelper {
	static Logger logger = LoggerFactory.getLogger(FileSystemHelper.class);

	public static void ensureFolderExists(String path) throws FileSystemHelperException {
		FileConnection fconn = null;
		try {
			fconn = (FileConnection) Connector.open(path, Connector.READ_WRITE);
			if (!fconn.exists()) {
				fconn.close();

				String parentDir = path.substring(0, path.lastIndexOf('/', path.length() - 2) + 1);
				ensureFolderExists(parentDir);
				fconn = (FileConnection) Connector.open(parentDir);
				if (!fconn.exists() || !fconn.isDirectory() || !fconn.canWrite()) {
					throw new FileSystemHelperException(FileSystemHelperException.ENSIURE_FOLDER_EXISTS_EXCEPTION, "Cannot create dir in parent dir.");
				} else {
					fconn = (FileConnection) Connector.open(path, Connector.READ_WRITE);
					fconn.mkdir();
					fconn.close();
				}
			}
		} catch (IOException e) {
			throw new FileSystemHelperException(FileSystemHelperException.ENSIURE_FOLDER_EXISTS_EXCEPTION, e.toString());
		} finally {
			FileConnectionHelper.closeConnection(fconn);
		}

	}

	public static class FileSystemHelperException extends Exception {

		private int errCode;

		public FileSystemHelperException(int errorCode) {
			super();
			errCode = errorCode;
		}

		public FileSystemHelperException(int errorCode, String msg) {
			super(msg);
			errCode = errorCode;
		}

		public int getErrCode() {
			return errCode;
		}

		public static final int ENSIURE_FOLDER_EXISTS_EXCEPTION = 0;
	}

	public static void deleteDirectory(String dir) throws IOException {

		FileConnection fconn = null;
		try {
			fconn = (FileConnection) Connector.open(dir);
			if (!fconn.exists() || !fconn.isDirectory()) {
				fconn.close();
				return;
			}
			String path;
			Enumeration e = fconn.list();
			fconn.close();
			while (e.hasMoreElements()) {
				path = dir + e.nextElement().toString();
				if (path.endsWith(SEP)) {
					deleteDirectory(path);
				} else {
					delete(path);
				}

			}
			delete(dir);

		}  finally {
			FileConnectionHelper.closeConnection(fconn);
		}
	}

	private static void delete(String path) throws IOException {
		FileConnection fconn = null;
		try {
			fconn = (FileConnection) Connector.open(path);
			if (!fconn.exists()) {
				return;
			}
			fconn.delete();
		} finally {
			FileConnectionHelper.closeConnection(fconn);
		}
	}

	final static String SEP = getSeparator();

	private static String getSeparator() {
		String sep = "/";
		try {
			sep = System.getProperty("file.separator");
		} catch (Exception e) {
			logger.debug("Cannot get separator using system property 'file.separator':" + e.getClass() + e.getMessage());
		}
		return sep;
	}

}
